package net.dgg.dggcloud.service.jrcrm.common.webscoket;

import net.dgg.dggcloud.service.jrcrm.constant.CommonConstant;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.net.URLDecoder;
import java.util.Map;

/**
 * 这个的主要作用是取得当前请求中的用户名，并且保存到当前的WebSocketHandler中，以便确定WebSocketHandler所对应的用户，具体可参考HttpSessionHandshakeInterceptor
 *
 * @author tanghom
 */
public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            String userId = servletRequest.getServletRequest().getParameter("userId");
            String userName = servletRequest.getServletRequest().getParameter("userName");
            String loginName = servletRequest.getServletRequest().getParameter("loginName");
            attributes.put(CommonConstant.WEBSOCKET_USER_SESSION, Long.valueOf(userId));
            attributes.put(CommonConstant.WEBSOCKET_USER_LOGINNAME, loginName);
            attributes.put(CommonConstant.WEBSOCKET_USER_NAME, StringUtils.isEmpty(userName) ? "" : URLDecoder.decode(userName, "utf-8"));
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}